package com.example.rentianjituan.myhuanxin;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.EMCallBack;
import com.easemob.chat.EMChat;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMMessage;
import com.easemob.chat.TextMessageBody;

public class MainActivity extends AppCompatActivity {
    private ListView listView;
    private EditText editText;
    private Button button;
    private EMConversation conversation;
    private String toChatUsername = "a";
    private DataAdpter adpter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        init();
        conversation = EMChatManager.getInstance().getConversation(toChatUsername);
        adpter = new DataAdpter();
        listView.setAdapter(adpter);
        registListener();
        EMChat.getInstance().setAppInited();
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (editText.getText().length() == 0) {
                    Toast.makeText(getApplicationContext(), "消息不能为空", Toast.LENGTH_SHORT).show();
                } else {
                    //获取到与聊天人的会话对象。参数username为聊天人的userid或者groupid，后文中的username皆是如此
                    EMConversation conversation = EMChatManager.getInstance().getConversation(toChatUsername);
                    //创建一条文本消息
                    EMMessage message = EMMessage.createSendMessage(EMMessage.Type.TXT);
                    //如果是群聊，设置chattype,默认是单聊
//                message.setChatType(EMMessage.ChatType.GroupChat);
                    //设置消息body
                    TextMessageBody txtBody = new TextMessageBody(editText.getText().toString());
                    message.addBody(txtBody);
                    //设置接收人
                    message.setReceipt(toChatUsername);
                    //把消息加入到此会话对象中
                    conversation.addMessage(message);

                    adpter.notifyDataSetChanged();
                    listView.setAdapter(adpter);
                    listView.setSelection(listView.getCount() - 1);
                    editText.setText("");
                    //发送消息
                    EMChatManager.getInstance().sendMessage(message, new EMCallBack() {
                        @Override
                        public void onSuccess() {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(MainActivity.this, "发送成功", Toast.LENGTH_SHORT).show();
                                }
                            });
                        }

                        @Override
                        public void onError(int i, String s) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
//                                Toast.makeText(MainActivity.this, "error", Toast.LENGTH_SHORT).show();
                                }
                            });
                        }

                        @Override
                        public void onProgress(int i, String s) {

                        }

                    });
                }
            }
        });
    }

    /**
     * 只有注册了广播才能接收到新消息，目前离线消息，在线消息都是走接收消息的广播
     * （离线消息目前无法监听，在登录以后，接收消息广播会执行一次拿到所有的离线消息）
     */
    private void registListener() {

        NewMessageBroadcastReceiver msgReceiver = new NewMessageBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter(EMChatManager.getInstance().getNewMessageBroadcastAction());
        intentFilter.setPriority(3);
        registerReceiver(msgReceiver, intentFilter);
    }

    private void init() {
        listView = (ListView) findViewById(R.id.listview);
        button = (Button) findViewById(R.id.send);
        editText = (EditText) findViewById(R.id.intput_content);
    }

    private class NewMessageBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            // 注销广播
            abortBroadcast();

            // 消息id（每条消息都会生成唯一的一个id，目前是SDK生成）
            String msgId = intent.getStringExtra("msgid");
            //发送方
            String username = intent.getStringExtra("from");
            // 收到这个广播的时候，message已经在db和内存里了，可以通过id获取mesage对象
            EMMessage message = EMChatManager.getInstance().getMessage(msgId);
            EMConversation conversation = EMChatManager.getInstance().getConversation(username);
            // 如果是群聊消息，获取到group id
            if (message.getChatType() == EMMessage.ChatType.GroupChat) {
                username = message.getTo();
            }
            if (!username.equals(username)) {
                // 消息不是发给当前会话，return
                return;
            }
            conversation.addMessage(message);
            adpter.notifyDataSetChanged();
            listView.setAdapter(adpter);
            listView.setSelection(listView.getCount() - 1);
        }
    }

    private class DataAdpter extends BaseAdapter {
        TextView textView;

        @Override
        public int getCount() {
            return conversation.getAllMessages().size();
        }

        @Override
        public Object getItem(int position) {
            return conversation.getAllMessages().get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            EMMessage message = conversation.getAllMessages().get(position);
            TextMessageBody body = (TextMessageBody) message.getBody();
            if (message.direct == EMMessage.Direct.RECEIVE) {
                if (message.getType() == EMMessage.Type.TXT) {
                    convertView = LayoutInflater.from(MainActivity.this).inflate(R.layout.layout_item, null);
                    textView = (TextView) convertView.findViewById(R.id.item_tv);
                    textView.setText(body.getMessage());
                }
            } else {
                if (message.getType() == EMMessage.Type.TXT) {
                    convertView = LayoutInflater.from(MainActivity.this).inflate(R.layout.layout_item1, null);
                    TextView textViewContent = (TextView) convertView.findViewById(R.id.item_tv1);
                    textViewContent.setText(body.getMessage());
                }
            }

            return convertView;
        }
    }
}
